package com.example.other.netty.imdemo;

import com.example.other.netty.endecode.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.UUID;

public class IMClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUserName("GGGGj");
        loginRequestPacket.setPassword("jjjjG");
        ByteBuf byteBuf = PacketCodec.encode(loginRequestPacket);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodec.decode(byteBuf);
        if(packet instanceof LoginResponsePacket){
            LoginResponsePacket responsePacket = (LoginResponsePacket) packet;
            if(responsePacket.getFlag() == 1){
                LoginUtil.markAsLogin(ctx.channel());
                System.out.println("登录成功。。。");
            }else{
                System.out.println("登录失败。。。");
            }
        }else if(packet instanceof MessageResponsePacket){
            MessageResponsePacket messageResponsePacket = (MessageResponsePacket)packet;
            System.out.println("收到服务端回复：" + messageResponsePacket.getMessage());
        }
    }
}
